// 导出页面为PDF格式
import html2Canvas from 'html2canvas'
import JsPDF from 'jspdf/dist/jspdf.debug.js'
export default {
  install(Vue, options) {
    Vue.prototype.getPdf = function (printClass, cb) {
      var title = this.htmlTitle
      let reportPages = document.querySelectorAll(printClass);
      let PDF = new JsPDF('', 'pt', 'a4');
      let pageImages = {};
      let counter = 0;
      let canvasArr = []

      Array.from(reportPages).forEach((el, index) => {
        html2Canvas(el, {allowTaint: true}).then((canvas) => {
          let pageImage = canvas.toDataURL('image/jpeg', 1.0);
          pageImages[index] = pageImage;
          canvasArr[index] = canvas
          counter++;
        });
      });
      let interval = setInterval(() => {
        if (counter === reportPages.length) {
          for (let i = 0; i < reportPages.length; i++) {
            PDF.addImage(pageImages[i], 'jpeg', 0, 0, 595.28, 592.28 / canvasArr[i].width * canvasArr[i].height);
            if (i !== reportPages.length - 1) PDF.addPage();
          }
          PDF.save('学生报告.pdf');
          cb && cb()
          clearInterval(interval);
        }
      }, 100);
    }
  }
}